package tv.huan.tencent.task;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import tv.huan.tencent.domain.CardBuyLog;
import tv.huan.tencent.domain.CardPool;
import tv.huan.tencent.mapper.CardBuyLogMapper;
import tv.huan.tencent.mapper.CardPoolMapper;
import tv.huan.tencent.service.ICardPoolService;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 卡池购买记录过期处理
 * 
 * @author ruoyi
 */
@Component("cardBuyLogExpireTask")
public class CardBuyLogExpireTask
{
    private static final Log logger = LogFactory.getLog(CardBuyLogExpireTask.class);

    @Autowired
    private AmqpTemplate rabbitmqTemplate;

    @Autowired
    private CardPoolMapper cardPoolMapper;

    @Autowired
    private CardBuyLogMapper cardBuyLogMapper;

    @Autowired
    private ICardPoolService cardPoolService;

    public void execute() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String now = format.format(new Date());
        logger.info(now + "日卡池购买记录过期处理任务开始===================" );
        List<CardBuyLog> cardBuyLogList = cardBuyLogMapper.selectCardBuyLogListByValidityDate(now);
        if (cardBuyLogList != null && cardBuyLogList.size() > 0){
            CardPool cp;
            for (CardBuyLog cbl : cardBuyLogList){
                cp = cardPoolMapper.selectCardPoolById(cbl.getCardId());
                logger.info("过期记录：" + cp.getCardName());
                cp.setPredictRemainder(cp.getPredictRemainder() - cbl.getPredictRemainder());
                cp.setActualRemainder(cp.getActualRemainder() - cbl.getActualRemainder());
                cardPoolMapper.updateCardPool(cp);
            }
        }
        //余量告警邮件
//        cardPoolService.checkCardPoolAndSendEmail();
    }

    /**
     * 将日期减天数得到新日期
     * @param value 天数
     * @return date
     */
    private static Date getDay(int value) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,value);
        return calendar.getTime();
    }

    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String yesterday = format.format(new Date());
        System.out.println(yesterday);
    }
}
